﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace commonV2
{
    public class MailMerge
    {
        // Word automation using C#
        // http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx
        // Example code

        //  myTypes.KeyValueItem[] terms = new myTypes.KeyValueItem[2];
        //  terms[0] = new myTypes.KeyValueItem("Name", "Dung Vu");
        //  terms[1] = new myTypes.KeyValueItem("DOB", "20/12/67");
        //  MailMerge("D:\\test\\name3.dot", terms , "d:\\test\\myfile.doc");

        public static void Merge(string templatePath, myTypes.KeyValueItem[] terms, string outDocPath, bool closeWindow)
        {
            //OBJECT OF MISSING "NULL VALUE"
            Object oMissing = System.Reflection.Missing.Value;
            //OBJECTS OF FALSE AND TRUE
            Object oFalse = false;

            //CREATING OBJECTS OF WORD AND DOCUMENT
            Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

            //SETTING THE VISIBILITY TO TRUE
            oWord.Visible = true;

            //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
            Object oTemplatePath = templatePath;

            //ADDING A NEW DOCUMENT FROM A TEMPLATE
            oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

            foreach (Microsoft.Office.Interop.Word.Field myMergeField in oWordDoc.Fields)
            {
                Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;

                String fieldText = rngFieldCode.Text;

                // ONLY GETTING THE MAILMERGE FIELDS
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    // THE TEXT COMES IN THE FORMAT OF
                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                    Int32 endMerge = fieldText.IndexOf("\\");
                    Int32 fieldNameLength = fieldText.Length - endMerge;
                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();
                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                    foreach (myTypes.KeyValueItem item in terms)
                    {
                        if (fieldName == item.Key)
                        {
                            myMergeField.Select();
                            //Some bug here : empty text is not merged
                            if(StringLibs.IsNullOrEmpty(item.Value))
                                 oWord.Selection.TypeText(" ");
                            else oWord.Selection.TypeText(item.Value);
                        }
                    }
                }
            }

            // If outDocPath= null : keep it in screen 
            if (StringLibs.IsNullOrEmpty(outDocPath)==false)
            {
                //THE LOCATION WHERE THE FILE NEEDS TO BE SAVED
                Object oSaveAsFile = (Object)outDocPath;
                oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing);

                //CLOSING THE FILE
                if (closeWindow)
                {
                    oWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                }
            }
            if (closeWindow)
            {
                //QUITTING THE APPLICATION
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
        }
    }
}
